// pages/set/set.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    userInfo: {},
    avatar: '',
    backgroundImg: "../../images/material/苏苏.jpg",
    birth: "2002-02-10",
    nameShow: false,
    genderShow: false,
    birthShow: false,
    introShow: false,
    max: 100,
    currentWordNumber: 0,
    value: "",
    radio: '',
    currentDate: '',
    maxDate: new Date().getTime(),
    formatter(type, value) {
      if (type === 'year') {
        return `${value}年`;
      } else if (type === 'month') {
        return `${value}月`;
      }
      return `${value}日`;
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    wx.request({
      url: `http://localhost:1234/person?userid=${wx.getStorageSync('userid')}`,
      method: "GET",
      header: {
        'content-type': "application/json"
      },
      success: res => {
        console.log(res.data);
        this.setData({
          userInfo: res.data,
          currentWordNumber: parseInt(res.data.intro.length)
        })
      },
      fail: err => {
        console.log(err);
      }
    })
  },
  //修改头像
  onAvatar: function () {
    var that = this;
    wx.chooseImage({
      // 可以指定是原图还是压缩图，默认二者都有
      sizeType: ["original", "compressed"],
      // 可以指定来源是相册还是相机，默认二者都有
      sourceType: ["album", "camera"],
      success: function (res) {
        // 返回选定照片的本地文件路径列表，tempFilePath 可以作为 img 标签的 src 属性显示图片
        wx.uploadFile({
          filePath: res.tempFilePaths[0],
          name: 'image',
          url: 'http://localhost:1234/person/set/avatar?userid=' + wx.getStorageSync('userid'),
          header: {//设置请求头
            'content-Type': 'multipart/form-data',
          },
          success: (res) => {
            console.log(JSON.parse(res.data));
            let userInfo = wx.getStorageSync('userInfo');
            userInfo.avatarUrl = JSON.parse(res.data).avatar;
            wx.setStorageSync('userInfo', userInfo);
            that.setData({
              userInfo: JSON.parse(res.data),
              avatar: 'http://localhost:1234/public/material/' + JSON.parse(res.data).avatar
            })
          }
        })
      },
    })
  },
  // 修改昵称
  onChange(event) {
    // event.detail 为当前输入的值
    console.log(event.detail);
    this.setData({
      value: event.detail
    })
  },

  nameOpen: function () {
    console.log("aa")
    this.setData({ nameShow: true });
  },
  nameClose: function () {
    this.setData({ nameShow: false });
  },
  nameSave: function () {
    if (this.data.value != this.data.userInfo.name) {
      wx.request({
        url: 'http://localhost:1234/person/set/name',
        method: "POST",
        header: {
          'content-type': "application/json"
        },
        data: JSON.stringify({
          name: this.data.value,
          userid: wx.getStorageSync('userid')
        }),
        success: res => {
          console.log(res.data);
          let userInfo = wx.getStorageSync('userInfo');
          userInfo.nickName = res.data.name;
          wx.setStorageSync('userInfo', userInfo);
          this.setData({
            userInfo: res.data,
            nameShow: false
          })
        },
        fail: err => {
          console.log(err);
        }
      })
    }
  },

  // 修改性别
  genderOpen: function () {
    console.log("aa")
    this.setData({ genderShow: true });
  },
  genderClose: function () {
    this.setData({ genderShow: false });
  },
  genderSave: function () {
    wx.request({
      url: 'http://localhost:1234/person/set/gender',
      method: "POST",
      header: {
        'content-type': "application/json"
      },
      data: JSON.stringify({
        gender: this.data.radio,
        userid: wx.getStorageSync('userid')
      }),
      success: res => {
        console.log(res.data);
        let userInfo = wx.getStorageSync('userInfo');
        userInfo.gender = res.data.sex;
        wx.setStorageSync('userInfo', userInfo);
        this.setData({
          userInfo: res.data,
          genderShow: false
        })
      },
      fail: err => {
        console.log(err);
      }
    })
  },
  genderChange(event) {
    this.setData({
      radio: event.detail
    });
  },

  genderClick(event) {
    console.log(event.currentTarget.dataset)
    const { name } = event.currentTarget.dataset;
    this.setData({
      radio: name
    });
  },

  // 修改生日
  birthOpen: function () {
    console.log(new Date(this.data.userInfo.birth).getTime())
    this.setData({
      currentDate: new Date(this.data.birth).getTime(),
      birthShow: true
    });
  },
  birthCancel() {
    this.setData({ birthShow: false });
  },
  birthConfirm() {
    let str = new Date(this.data.currentDate).toLocaleDateString();
    let birthArr = str.split('/');
    birthArr[1] = birthArr[1] < 10 ? "0" + birthArr[1] : birthArr[1];
    birthArr[2] = birthArr[2] < 10 ? "0" + birthArr[2] : birthArr[2];
    let birthStr = birthArr.join('-');
    this.setData({
      birth: birthStr,
      birthShow: false
    })
  },
  birthInput(event) {
    this.setData({
      currentDate: event.detail
    });
  },

  // 修改简介
  introOpen: function () {
    console.log("aa")
    this.setData({
      introShow: true
    });
  },
  introClose: function () {
    this.setData({
      introShow: false
    });
  },
  introSave: function () {
    if (this.data.value != this.data.userInfo.intro) {
      wx.request({
        url: 'http://localhost:1234/person/intro',
        method: "POST",
        header: {
          'content-type': "application/json"
        },
        data: JSON.stringify({
          value: this.data.value,
          userid: wx.getStorageSync('userid')
        }),
        success: res => {
          console.log(res.data);
          this.setData({
            userInfo: res.data,
            show: false
          })
        },

        fail: err => {
          console.log(err)
        }
      })
      this.setData({
        ['userInfo.intro']: this.data.value,
        introShow: false
      });
    }
  },
  getValueLength: function (e) {
    let value = e.detail.value
    let len = parseInt(value.length)
    if (len > 100) return;
    this.setData({
      value: value,
      currentWordNumber: len //当前字数 
    })
  },

  // 修改背景图
  backOpen: function () {
    var that = this;
    wx.chooseImage({
      // 可以指定是原图还是压缩图，默认二者都有
      sizeType: ["original", "compressed"],
      // 可以指定来源是相册还是相机，默认二者都有
      sourceType: ["album", "camera"],
      success: function (res) {
        // 返回选定照片的本地文件路径列表，tempFilePath 可以作为 img 标签的 src 属性显示图片
        wx.uploadFile({
          filePath: res.tempFilePaths[0],
          name: 'image',
          url: 'http://localhost:1234/person/set/back?userid=' + wx.getStorageSync('userid'),
          header: {//设置请求头
            'content-Type': 'multipart/form-data',
          },
          success: (res) => {
            console.log(JSON.parse(res.data));
            that.setData({
              userInfo: JSON.parse(res.data),
              temp: 'http://localhost:1234/public/material/' + JSON.parse(res.data).perface
            })
          }
        })
      },
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    let userInfo = wx.getStorageSync('userInfo');
    this.setData({
      radio: userInfo.gender
    })
    wx.request({
      url: 'http://localhost:1234/person?userid=' + wx.getStorageSync('userid'),
      method: "GET",
      header: {
        'content-type': "application/json"
      },
      success: res => {
        console.log(res.data);
        this.setData({
          temp: 'http://localhost:1234/public/material/' + res.data.perface
        })
        let userInfo = wx.getStorageSync('userInfo');
        if (userInfo.avatarUrl.includes('//')) {
          this.setData({
            avatar: userInfo.avatarUrl
          })
        }
        else {
          this.setData({
            avatar: 'http://localhost:1234/public/material/' + res.data.avatar
          })
        }
      },
      fail: err => {
        console.log(err);
      }
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})